package com.rowline.admin.module.study.jdknewfeature;

import java.util.Arrays;
import java.util.Collection;

/**
 * ClassName:StreamDemo
 * Created by 245167
 * on 2018/5/5  05:22
 * description:
 */
public class StreamDemo{

    private enum Status {
        OPEN, CLOSED
    };

    private static final class Task {
        private final Status status;
        private final Integer points;

        Task( final Status status, final Integer points ) {
            this.status = status;
            this.points = points;
        }

        public Integer getPoints() {
            return points;
        }

        public Status getStatus() {
            return status;
        }

        @Override
        public String toString() {
            return String.format( "[%s, %d]", status, points );
        }
    }

    public static void main(String[] args) {

        final Collection< Task > tasks = Arrays.asList(
                new Task( Status.OPEN, 5 ),
                new Task( Status.OPEN, 13 ),
                new Task( Status.CLOSED, 8 )
        );


        /*
        step1，task集合被转换化为其相应的stream表示。
        step2，filter操作过滤掉状态为CLOSED的task。
        step3，mapToInt操作通过Task::getPoints这种方式调用每个task实例的getPoints方法把Task的stream转化为Integer的stream。
        step4，用sum函数把所有的分数加起来，得到最终的结果。
        */
        final long totalPointsOfOpenTasks = tasks
                .stream()
                .filter( task -> task.getStatus() == Status.OPEN )
                .mapToInt( Task::getPoints )
                .sum();

        System.out.println( "Total points: " + totalPointsOfOpenTasks );

    }


}
